package com.zzq.base.awesome.component;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.zzq.base.awesome.api.entity.User;
import com.zzq.base.awesome.entity.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.zzq.base.awesome.entity.CommonData.EXPORESTIME;

@Component
@Slf4j
public class UserCache implements ApplicationListener<ApplicationStartedEvent> {
    private Cache<String,UserDetail> cache;
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        cache = CacheBuilder.newBuilder().
                expireAfterWrite(EXPORESTIME, TimeUnit.MILLISECONDS).
                maximumSize(1000).build();
        log.info("生成用户缓存");
    }

    public UserDetail getUserFromCache(String username) {
        UserDetail u =  cache.getIfPresent(username);
        if (log.isDebugEnabled()) {
            log.debug("Cache hit: " + (u != null) + "; username: " + username);
        }
        return u;
    }

    public boolean isUserIn(String sign){
        log.info("get: " + sign);
        return this.cache.getIfPresent(sign) == null;
    }

    public void putUserInCache(UserDetail user) {
        if (log.isDebugEnabled()) {
            log.debug("Cache put: " + user.getSign());
        }
        this.cache.put(user.getSign(), user);
    }

    public void removeUserFromCache(UserDetail user) {
        if (log.isDebugEnabled()) {
            log.debug("Cache remove: " + user.getSign());
        }
        this.removeUserFromCache(user.getSign());
    }

    public void removeUserFromCache(String username) {
        this.cache.invalidate(username);
    }

    public static void main(String[] args) {
        UserCache userCache = new UserCache();
        userCache.onApplicationEvent(null);
        log.info("生成用户缓存");
        User u = new User();
        u.setId(1);
        u.setAccount("asdas");
        userCache.putUserInCache(u);
        System.gc();
    }
}
